Autokey Cipher

Module 01 / Lesson 02

Visual Explanation


How it Works

The Autokey Cipher is a polyalphabetic substitution cipher. It is more secure than the Vigenère cipher because it doesn't repeat the keyword. Instead, it uses a "seed" keyword and then appends the message itself to the key.


Encryption Logic:

To encrypt, we take the keyword and the plaintext. The key stream is created by: Key = Keyword + Plaintext. Each character is then shifted using the same Tabula Recta logic as Vigenère.

Plaintext: ATTACKATDAWN
Keyword: QUEEN
Full Key: QUEENATTACKA

Python Implementation

def autokey_encrypt(plaintext, keyword):
    plaintext = plaintext.upper().replace(" ", "")
    keyword = keyword.upper()
    
    # Generate the full key by appending plaintext
    key = (keyword + plaintext)[:len(plaintext)]
    
    ciphertext = ""
    for p, k in zip(plaintext, key):
        # Shift formula: (P + K) mod 26
        c = chr(((ord(p) - 65) + (ord(k) - 65)) % 26 + 65)
        ciphertext += c
    return ciphertext

# Example Usage
print(autokey_encrypt("HELLO", "KEY")) # Output: RIJVS